package com.roc.web.action.merinfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoSearchBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblMchtInf;
import com.roc.service.IMerchantServices;
import com.roc.service.IUserService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
@Component
@Namespace("/mer")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ReuploadMerinfoPictureAction extends PaginationBaseAction{
	
	static Logger logger = Logger.getLogger(ReuploadMerinfoPictureAction.class);
	
	private ReuploadMerinfoPictureSerachCondition searchCondition;
	
	@Autowired
	IPowerInfoService iPowerInfoService;
	
	@Autowired
	IPageService pageService;
	
	@Autowired
	IMerchantServices merinfoService;
	
	@Autowired
	private IUserService  userService;
	
	private TblMchtInf merinfo; // 商户临时表
	
	private Double zwPayRate;
	
	private String provice32;//省份32域名
	
	
	/**
	 * 查询List
	 * */
	@Action(value = "reuploadPicInfo", results = {	
			@Result(name =SUCCESS, location = "/pages/merinfo/reuploadPicInfo.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String merinfoinfoComplete() {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if (searchCondition == null) {
				searchCondition = (ReuploadMerinfoPictureSerachCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new ReuploadMerinfoPictureSerachCondition();
				}
			}
			
			//机构管理员  运营  受理市场运营 系统管理员   风控 
			if (!Role.O_MANAGER.getCode().equals(op.getRoleType())
					&& !Role.OPERATORS_COMM.getCode().equals(
							op.getRoleType())
					&& !Role.SYSTEM.getCode().equals(op.getRoleType()) && !Role.OPERATORS_LEAD.getCode().equals(op.getRoleType())
					&& !Role.RISK_CONTROL_OPERATORS.getCode().equals(op.getRoleType()) 
					&& !Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())) {
				addActionError("无权限访问!!!");
				return ERROR;
			}
			
			
			//运营角色转换  
			Map<String, String> map=iPowerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
            
			if (Role.AGENT.getCode().equals(superRole)) {
				addActionError("无权限访问!!!");
				return ERROR;
			}
            
            
//           	searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
            searchCondition.setRoleId(superRole);// 角色
            searchCondition.setOpId(opRealId);//当前人员id
            searchCondition.setMerinfoFlag(0);
//			searchCondition.setStatus(MerinfoStatus.S_0.getCode());//正常
			/*if(!"".equals(op.getOneagentid())){
				searchCondition.setOneOrgCode(op.getOneagentid());//机构号
			}*/
			//querySon(op);
			handleResultList(op);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
			return SUCCESS;
	}
		
	/**
	 * 修改图片页面初始化
	 * */
	@Action(value = "saveReuploadPicInfoInit", 
			results = { @Result(name = SUCCESS, location = "/pages/merinfo/saveReuploadPicInfo.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String saveReuploadPicInfoInit() {
		try {
			if (null==merinfo || merinfo.getId() == null || merinfo.getId().equals("")) {
				addActionError("异常，获取商户信息失败");
				return ERROR;
			}
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			merinfo=merinfoService.queryMerinfoDetailInfo(merinfo.getId(), true,op.getAgentType());
			if(merinfo != null && "".equals(Constance.Null2EmptyTrim(merinfo.getBusiRang()))){
				merinfo.setBusiRang(merinfo.getId());
			}
			getRequest().setAttribute("mcc", ConfigProperties.getHyMccTypeProperties());//mcc
			/*getRequest().setAttribute("provinesMap", ConfigProperties.getUnionProviceProperties());//32域省份*/
			//查询32域信息
			String code32=userService.queryAreaDetailBy32Code(merinfo.getUcBccd());
			getRequest().setAttribute("code32",code32);
			getRequest().setAttribute("choosePosName",ConfigProperties.getSysDB1("PROD_CD",true).get(merinfo.getProductCode()));
			if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD())){
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getDirectProductList(ConfigMerinfoUtil.DIRECT_FUNCTION_ALL, true));//获取开通直连产品信息
			}else{
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getPosFunction(ConfigMerinfoUtil.ALL_FUNCTION, true));//开通产品信息
			}
			getRequest().setAttribute("org", op.getOrgCode());//机构
		} catch (Exception e) {
			logger.error("加载商户基本信息出错", e);
			addActionError("加载商户基本信息出错");
		}
		return SUCCESS;
	}
	
	
	/**
	 * 保存图片信息
	 * */
	@Action(value = "saveReuploadPicInfo", 
			results = { @Result(name =SUCCESS, type = "chain", location = "reuploadPicInfo"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String saveReuploadPicInfo() {
		 
		try {
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);//当前操作员
			//简单校验
			if(merinfo.getId()==null || "".equals(merinfo.getId())){
				addActionMessage("商户号为空"); return SUCCESS;
			}
			
			if(merinfo.getBusiRang()==null || "".equals(merinfo.getBusiRang())){
				addActionMessage("临时商户号为空"); return SUCCESS;
			}
			String returnInfo=merinfoService.modifyPicInfo(merinfo, op);
			addActionMessage(returnInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	
	/**
	 * 处理查询结果
	 * @throws Exception 
	 * @throws ServiceException 
	 * */
	private void handleResultList(Operators  op) throws Exception {
		try {
			int rows = pageService.countSQL(searchCondition);
			List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
			if (rows > 0) {
				searchRsList = pageService.findAllSQL(searchCondition,calcuStart(getCurrentPage()),Constance.PAGE_MAX_SIZE);
				if (searchRsList != null && searchRsList.size() > 0) {
					msList = handleDetail(searchRsList, op);
				}
			}
			/*if("48502000".equals(searchCondition.getOneOrgCode()) || "".equals(searchCondition.getOneOrgCode()) || searchCondition.getOneOrgCode() == null){
				searchCondition.setOperationFlag("1");	//系统管理员所属
			}else{
				searchCondition.setOperationFlag("2");	//机构所属
			}*/
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//统计次数
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("opid", op.getId());
//			getRequest().setAttribute("operationFlag", searchCondition.getOperationFlag());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			throw new Exception("查询失败",e);
		}
	 
	}
	
	//审核查询
		private List<MerinfoSearchBean> handleDetailFor05(List<Object> objList,Operators  op) throws Exception{
			List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
			try {
				Iterator iterator = objList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					MerinfoSearchBean msb = new MerinfoSearchBean();
					msb.setMid(Constance.Null2EmptyTrim(obj[0]));  //商户号
					msb.setMerName(Constance.Null2EmptyTrim(obj[1])); //商户简称
					msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));//商户注册名称
					msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));//机构名称
					msb.setPerName(Constance.Null2EmptyTrim(obj[4])); //商户联系人
					String phone=Constance.Null2EmptyTrim(obj[5]);//联系人手机号
					if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=phone && phone.length()>4){
						msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
					}else{
						msb.setPerPhone(phone);//手机号
					}
					msb.setInterContact(Constance.Null2EmptyTrim(obj[6])); //法人
					String cardNo=Constance.Null2EmptyTrim(obj[7]);//法人证件号
					if(null!=op.getAgentType() && !op.getAgentType().equals("1")  && null!=cardNo && cardNo.length()>4){
						msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
					}else{
						msb.setCardNo(cardNo);//证件号
					}
					msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));//营业执照
					msb.setAddr(Constance.Null2EmptyTrim(obj[9])); //地址
					msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
					msb.setCompanyName(Constance.Null2EmptyTrim(obj[11])); //所属分公司
					msb.setOneAgentName(Constance.Null2EmptyTrim(obj[12]));//所属一级代理
					msb.setAgentId(Constance.Null2EmptyTrim(obj[13]));//直属代理商
					
					msb.setRsvl(Constance.Null2EmptyTrim(obj[14]));//结算银行账户名称
					String account=Constance.Null2EmptyTrim(obj[15]);
					/*if(account!=null && account.length()>4){
						msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
					}else{*/
						msb.setRsvl3(account);//结算银行账户
					//}
					msb.setAmount1(Constance.Null2EmptyTrim(obj[16]));//结算银行名称
					msb.setAmount2(Constance.Null2EmptyTrim(obj[17]));//联行号
					/*String[] cycleList=merinfoService.queryMchtBizDealArray(msb.getMid(),false,true);//根据商户查询结算周期
					msb.setMerCycle(cycleList);*/
					msb.setEngName(Constance.Null2EmptyTrim(obj[18]));
					msb.setGroupCd(Constance.Null2EmptyTrim(obj[21]));
					String[] productCodeFlag=merinfoService.queryMchtBizDealArray(msb.getMid(), true, false);
					String[] cycleList={"",""};
					if(Constant.STR_NUMBER_ONE.equals(msb.getGroupCd()) && (Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
							Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){
						cycleList[0]=Constance.Null2EmptyTrim(obj[26]);
						if(null!=Constance.Null2EmptyTrim(obj[27]) && !Constance.Null2EmptyTrim(obj[27]).equals("")){
							String j="";
							if(null!=cycleList[0] && !cycleList[0].equals("")){
								j="+";
							}
							cycleList[1]=j+Constance.Null2EmptyTrim(obj[27]);
						}
					}else{
						cycleList[0]=Constance.Null2EmptyTrim(obj[19]);
						if(null!=Constance.Null2EmptyTrim(obj[20]) && !Constance.Null2EmptyTrim(obj[20]).equals("")){
							String j="";
							if(null!=cycleList[0] && !cycleList[0].equals("")){
								j="+";
							}
							cycleList[1]=j+Constance.Null2EmptyTrim(obj[20]);
						}
					}
					msb.setMerCycle(cycleList);
					msb.setNationCd(Constance.Null2EmptyTrim(obj[22]));
					msb.setIsGroup(Constance.Null2EmptyTrim(obj[23]));
					msb.setRecUpdOpr(Constance.Null2EmptyTrim(obj[25]));	//rec_upd_opr
					msList.add(msb);
				}
			} catch (Exception e) {
				throw new Exception("处理结果失败",e);
			}
			return msList;
		}
		//查询状态为领件的处理方法
			private List<MerinfoSearchBean> handleDetail(List<Object> objList,Operators  op) throws Exception{
				List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
				try {
					Iterator iterator = objList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						MerinfoSearchBean msb = new MerinfoSearchBean();
						msb.setMid(Constance.Null2EmptyTrim(obj[0]));
						msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
						msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
						msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
						msb.setPerName(Constance.Null2EmptyTrim(obj[4]));
						String phone=Constance.Null2EmptyTrim(obj[5]);
						if(null!=op.getAgentType() && !op.getAgentType().equals("1") && phone!=null && phone.length()>3){
							msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
						}else{
							msb.setPerPhone(phone);//手机号
						}
						msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));
						String cardNo=Constance.Null2EmptyTrim(obj[7]);
						if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=cardNo && cardNo.length()>4){
							msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
						}else{
							msb.setCardNo(cardNo);//证件号
						}
						msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));
						msb.setAddr(Constance.Null2EmptyTrim(obj[9]));
						msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
						msb.setCompanyName(Constance.Null2EmptyTrim(obj[11])); //所属分公司
						msb.setOneAgentName(Constance.Null2EmptyTrim(obj[12]));//所属一级代理
						msb.setAgentId(Constance.Null2EmptyTrim(obj[13]));//直属代理商
						
						msb.setRsvl(Constance.Null2EmptyTrim(obj[14]));//结算银行账户名称
						String account=Constance.Null2EmptyTrim(obj[15]);
						msb.setGroupCd(Constance.Null2EmptyTrim(obj[20])); //商户类型
						/*if(account!=null && account.length()>4){
							msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
						}else{*/
							msb.setRsvl3(account);//结算银行账户
						//}
						msb.setAmount1(Constance.Null2EmptyTrim(obj[16]));//结算银行名称
						msb.setAmount2(Constance.Null2EmptyTrim(obj[17]));//联行号
						/*String[] cycleList=merinfoService.queryMchtBizDealArray(msb.getMid(),false,true);//根据商户查询结算周期
						msb.setMerCycle(cycleList);*/
						String[] productCodeFlag=merinfoService.queryMchtBizDealArray(msb.getMid(), true, false);
						String[] cycleList={"",""};
						if(Constant.STR_NUMBER_ONE.equals(msb.getGroupCd()) && (Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
								Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){
							cycleList[0]=Constance.Null2EmptyTrim(obj[25]);
							if(null!=Constance.Null2EmptyTrim(obj[26]) && !Constance.Null2EmptyTrim(obj[26]).equals("")){
								String j="";
								if(null!=cycleList[0] && !cycleList[0].equals("")){
									j="+";
								}
								cycleList[1]=j+Constance.Null2EmptyTrim(obj[26]);
							}
						}else{
							cycleList[0]=Constance.Null2EmptyTrim(obj[18]);
							if(null!=Constance.Null2EmptyTrim(obj[19]) && !Constance.Null2EmptyTrim(obj[19]).equals("")){
								String j="";
								if(null!=cycleList[0] && !cycleList[0].equals("")){
									j="+";
								}
								cycleList[1]=j+Constance.Null2EmptyTrim(obj[19]);
							}
						}
						msb.setMerCycle(cycleList);
						msb.setNationCd(Constance.Null2EmptyTrim(obj[21]));
						msb.setIsGroup(Constance.Null2EmptyTrim(obj[22]));
						//rec_upd_opr
						msb.setRecUpdOpr(Constance.Null2EmptyTrim(obj[24]));
						msList.add(msb);
					}
				} catch (Exception e) {
					throw new Exception("处理结果失败",e);
				}
				return msList;
			}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_REUPLOAD_PIC_QUERY, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (ReuploadMerinfoPictureSerachCondition) getSession().getAttribute(SEARCH_SESSION_REUPLOAD_PIC_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public ReuploadMerinfoPictureSerachCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			ReuploadMerinfoPictureSerachCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public TblMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblMchtInf merinfo) {
		this.merinfo = merinfo;
	}

	public Double getZwPayRate() {
		return zwPayRate;
	}

	public void setZwPayRate(Double zwPayRate) {
		this.zwPayRate = zwPayRate;
	}

	public String getProvice32() {
		return provice32;
	}

	public void setProvice32(String provice32) {
		this.provice32 = provice32;
	}

	
}
